import { createRouter, createWebHistory } from 'vue-router'
import routes from './routes/index.js'
import { useUserStore } from '@/store/user/index.js'

const router = createRouter({
    history: createWebHistory(),
    routes
})

router.beforeEach((to, from, next) => {
    const userStore = useUserStore()

    // 判断是否需要登录才能访问
    if (to.meta.requireAuth) {
        if (userStore.token) {
            next() // 有 token 继续访问
        } else {
            // ❗无 token → 跳登录页，并带上来源路径
            next({
                path: '/login',
                query: { redirect: to.fullPath }
            })
        }
    } else {
        next() // 不需要登录直接放行
    }
})

export default router
